{ "metadata": { "name": "", "signature": "sha256:c3e33dc11003c69beadcd211d1246a49287debf8cbc4b6561aa01c46e5ea31b1" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "The brythonmagic extension has been tested on:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import IPython\n", "IPython.version_info" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "brythonmagic installation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Just type the following:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%install_ext https://raw.github.com/kikocorreoso/brythonmagic/master/brythonmagic.py" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%load_ext brythonmagic" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And load the brython js lib in the notebook:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%HTML\n", "" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Warning" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to load javascript libraries in a safety way you should try to use https instead of http when possible (read more [here](http://mail.scipy.org/pipermail/ipython-dev/2014-July/014572.html)). If you don't trust the source and/or the source cannot be loaded using https then you could download the javascript library and load it from a local location." ] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Usage:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The brythonmagic provides you a cell magic, `%%brython`, to run brython code and show the results in a html `div` tag below the code cell.\n", "\n", "You can use several options:\n", "\n", "* -p, --print: will show you the generated html code below the results obtained from the brython code.\n", "\n", "\n", "* -c, --container: you can define de name of the `div` container in case you want to 'play' with it in other cell. If you don't define an output the `div` will have and `id` with the following format 'brython-container-[random number between 0 and 999999]'\n", "\n", "\n", "* -i, --input: you can pass variables defined in the Python namespace separated by commas. If you pass a python list it will be converted to a brython list, a python tuple will be converted to a brython tuple, a python dict will be converted to a brython dict, a python string will be converted to a brython string.\n", "\n", "\n", "* -h, --html: you can pass a string with html markup code. This html code will be inserted inside the div container. In this way you can avoid the generation of HTML markup code via a Brython script so you can separate the layout from the 'action'.\n", "\n", "\n", "* -s, --script: Use this option to provide and id to the script defined in the Brython code cell. Also, this value could be used to run the code of this cell in other brython cells.\n", "\n", "\n", "* -S, --scripts: Use this option to run code previously defined in other Brython code cells. The values should be the provided values in the -s/--script option in other Brython code cells.\n", "\n", "* -f, --fiddle: With this option, the code in the cell will be automatically uploaded to [gist.github.com/](https://gist.github.com/) as an anonymous gist with several files in it. This files will be used to create an anonymous 'fiddle' on [jsfiddle.net](http://jsfiddle.net). Finally, some links will be printed in the output linking to the gist and the fiddle. See an example here ([https://gist.github.com/anonymous/b664e8b4617afc09db6c](https://gist.github.com/anonymous/b664e8b4617afc09db6c) and [http://jsfiddle.net/gh/gist/library/pure/b664e8b4617afc09db6c/](http://jsfiddle.net/gh/gist/library/pure/b664e8b4617afc09db6c/))\n", "\n", "* -e, --embedfiddle: With this option, the code in the cell will be automatically uploaded to [gist.github.com/](https://gist.github.com/) as an anonymous gist with several files in it. This files will be used to create an anonymous 'fiddle' on [jsfiddle.net](http://jsfiddle.net). Finally, some links will be printed in the output linking to the gist and the fiddle and an iframe will be created showing the fiddle on [jsfiddle.net](http://jsfiddle.net).\n", "\n", "[WARNING] This options may change as the brythonmagic is in active development." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-p, --print` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following example shows the use of the `-p`, `--print` option. \n", "\n", "[HINT] The result of the print is shown in the javascript console of your browser." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -p\n", "print('hello world!')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-c, --container` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the following example can be seen the use of the `-c`, `--container`. The `-p` is also used to show you the result. See the `id` attribute of the `div` tag created:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c my_container -p\n", "from browser import doc, html\n", "\n", "# This will be printed in the js console of your browser\n", "print('Hello world!')\n", "\n", "# This will be printed in the container div on the output below\n", "doc[\"my_container\"] <= html.P(\"This text is inside the div\", \n", " style = {\"backgroundColor\": \"cyan\"})" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-i, --input` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example you can see how the data are passed to brython from python using the `-i` or `--input` option. First, we create some data in a regular Python cell." ] }, { "cell_type": "code", "collapsed": false, "input": [ "data_list = [1,2,3,4]\n", "\n", "data_tuple = (1,2,3,4)\n", "\n", "data_dict = {'one': 1, 'two': 2}\n", "\n", "data_str = \"\"\"\n", "Hello\n", "GoodBye\n", "\"\"\"\n", "\n", "# A numpy array can be converted to a list and you will obtain a brython list\n", "import numpy as np\n", "data_arr = np.empty((3,2))\n", "data_arr = data_arr.tolist()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now, the created data are passed to Brython and used in the Brython code cell. **Remember that only Python lists, tuples, dicts and strings are allowed as inputs**." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c p2b_data_example -i data_list data_tuple data_dict data_str data_arr\n", "from browser import doc, html\n", "\n", "doc[\"p2b_data_example\"] <= html.P(str(data_list))\n", "doc[\"p2b_data_example\"] <= html.P(str(type(data_list)))\n", "\n", "doc[\"p2b_data_example\"] <= html.P(str(data_tuple))\n", "doc[\"p2b_data_example\"] <= html.P(str(type(data_tuple)))\n", "\n", "doc[\"p2b_data_example\"] <= html.P(str(data_dict))\n", "doc[\"p2b_data_example\"] <= html.P(str(type(data_dict)))\n", "\n", "doc[\"p2b_data_example\"] <= html.P(data_str.replace('Hello', 'Hi'))\n", "doc[\"p2b_data_example\"] <= html.P(str(type(data_str)))\n", "\n", "doc[\"p2b_data_example\"] <= html.P(str(data_arr))\n", "doc[\"p2b_data_example\"] <= html.P(str(type(data_arr)))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-h, --html` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example you can see how to create some HTML code in a cell and then use that HTML code in the brython cell. In this way you do not need to create the HTML code via scripting with Brython." ] }, { "cell_type": "code", "collapsed": false, "input": [ "html = \"\"\"\n", "
Hi
\n", "\"\"\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c html_ex -h html\n", "from browser import doc\n", "\n", "doc[\"paragraph\"].style = {\"color\": \"yellow\",\n", " \"fontSize\": \"100px\",\n", " \"lineHeight\": \"150px\",\n", " \"textAlign\": \"center\",\n", " \"backgroundColor\": \"black\"}" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-s, --script` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this option you are creating a reference of the code in the Brython cell (e.g., an `id` of the HTML `script` tag created to run the Brython code). So, if you need to use the code of the Brython cell in a future Brython cell you could reference it by its `id`. Let's see this on an example (the `-p` option is used to show you the generated code and how the `id` of the `script` tag is created):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -s my_dummy_function -p\n", "def dummy_function(some_text):\n", " print(some_text)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-S, --scripts` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This option could be used to call code created in a previous Brython code cell using its `id` (see the `-s` option above). In the following code cell we will use the `dummy_function` created in another Brython code cell. The `dummy_function` was created in a `script` tag with an `id=\"my_dummy_function\"`.\n", "\n", "[HINT] The result of the Brython code cell below is shown in the javascript console of your browser." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -S my_dummy_function\n", "dummy_function('Hi')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-f, --fiddle` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this option, the code in the cell will be automatically uploaded to [gist.github.com/](https://gist.github.com/) as an anonymous gist with several files in it. This files will be used to create an anonymous 'fiddle' on [jsfiddle.net](http://jsfiddle.net). Finally, some links will be printed in the output linking to the gist and the fiddle." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -f\n", "from browser import alert\n", "alert('hello world from jsfiddle!')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "`-e, --embedfiddle` option" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this option, the code in the cell will be automatically uploaded to [gist.github.com/](https://gist.github.com/) as an anonymous gist with several files in it. This files will be used to create an anonymous 'fiddle' on [jsfiddle.net](http://jsfiddle.net). Finally, some links will be printed in the output linking to the gist and the fiddle and an iframe will be created showing the fiddle on [jsfiddle.net](http://jsfiddle.net)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -e\n", "from browser import alert\n", "alert('hello world from jsfiddle!')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "How to use Brython in the IPython notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First step should be to learn the brython documentation. You can find the docs here:\n", "\n", "http://brython.info/doc/en/index.html?lang=en\n", "\n", "In the following section I will show you some dummy examples." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Hello world example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example let's see how to pop up an alert window. This could be an standard 'Hello world!' example in the Brython world." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython\n", "from browser import alert\n", "\n", "alert('Hello world!, Welcome to the brythonmagic!')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Simple example, writing some numbers in the `div` container" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example we just write inside a `
` ten numbers using a `

` tag for each number.\n", "\n", "[HINT] To see the line numbers in the code cell just go to the cell and press **`-m`** and then **`l`**.\n", "\n", "* Line 2: We import the libraries to use\n", "* Line 4: A for loop :-P\n", "* Line 10: We create a `P` tag and write the value of `i` inside. Finally, add the `P` element to the selected `div`, in this case the `div` with \"simple_example\" `id` attribute." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c simple_example\n", "from browser import doc, html\n", "\n", "for i in range(10):\n", " doc[\"simple_example\"] <= html.P(i)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "A more useful example: A multiplication table" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the following cell we create a multiplication table. First, we create a `table` tag. We append the table rows and cells (`TR` and `TD` tags) and, finally, we append the final table to the `div` with \"table\" `id` attribute." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c table\n", "from browser import doc, html\n", "\n", "table = html.TABLE()\n", "\n", "for i in range(10):\n", " color = ['cyan','#dddddd'] * 5\n", " table <= html.TR(\n", " html.TD(str(i+1) + ' x 2 =', style = {'backgroundColor':color[i]}) + \n", " html.TD((i+1)*2, style = {'backgroundColor':color[i]}))\n", "doc['table'] <= table" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Let's add some animation using HTML5 canvas technology..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the following example we draw a shape using the HTML5 `canvas`. Also, we add some controls to stop and animate the shape. The example has been adapted from the javascript example available [here](http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c canvas_example\n", "from browser.timer import request_animation_frame as raf\n", "from browser.timer import cancel_animation_frame as caf\n", "from browser import doc, html\n", "from time import time\n", "import math\n", "\n", "# First we create a table to insert the elements\n", "table = html.TABLE(cellpadding = 10)\n", "btn_anim = html.BUTTON('Animate', Id=\"btn-anim\", type=\"button\")\n", "btn_stop = html.BUTTON('Stop', Id=\"btn-stop\", type=\"button\")\n", "cnvs = html.CANVAS(Id=\"raf-canvas\", width=256, height=256)\n", "\n", "table <= html.TR(html.TD(btn_anim + btn_stop) +\n", " html.TD(cnvs))\n", "\n", "doc['canvas_example'] <= table\n", "# Now we access the canvas context\n", "ctx = doc['raf-canvas'].getContext( '2d' ) \n", "\n", "# And we create several functions in charge to animate and stop the draw animation\n", "toggle = True\n", "\n", "def draw():\n", " t = time() * 3\n", " x = math.sin(t) * 96 + 128\n", " y = math.cos(t * 0.9) * 96 + 128\n", " global toggle\n", " if toggle:\n", " toggle = False\n", " else:\n", " toggle = True\n", " ctx.fillStyle = 'rgb(200,200,20)' if toggle else 'rgb(20,20,200)'\n", " ctx.beginPath()\n", " ctx.arc( x, y, 6, 0, math.pi * 2, True)\n", " ctx.closePath()\n", " ctx.fill()\n", "\n", "def animate(i):\n", " global id\n", " id = raf(animate)\n", " draw()\n", "\n", "def stop(i):\n", " global id\n", " print(id)\n", " caf(id)\n", "\n", "doc[\"btn-anim\"].bind(\"click\", animate)\n", "doc[\"btn-stop\"].bind(\"click\", stop)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Interaction with other javascript libraries: D3.js" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Brython there is a javascript library that allows to access objects available in the javascript namespace. In this example we are using a javascript object (D3.js library) from Brython.\n", "\n", "So, in order to allow Brython to access to D3 first you should load the D3 library." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%HTML\n", "" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can access D3 objects using `JSObject` (see example below)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c simple_d3\n", "from browser import window, document, html\n", "from javascript import JSObject\n", "\n", "d3 = window.d3\n", "\n", "container = JSObject(d3.select(\"#simple_d3\"))\n", "svg = container.append(\"svg\").attr(\"width\", 100).attr(\"height\", 100)\n", "circle1 = svg.append(\"circle\").style(\"stroke\", \"gray\").style(\"fill\", \"gray\").attr(\"r\", 40)\n", "circle1.attr(\"cx\", 50).attr(\"cy\", 50).attr(\"id\", \"mycircle\")\n", "\n", "circle2 = svg.append(\"circle\").style(\"stroke\", \"gray\").style(\"fill\", \"white\").attr(\"r\", 20)\n", "circle2.attr(\"cx\", 50).attr(\"cy\", 50)\n", "\n", "def over(ev):\n", " document[\"mycircle\"].style.fill = \"blue\"\n", "\n", "def out(ev):\n", " document[\"mycircle\"].style.fill = \"gray\"\n", "\n", "document[\"mycircle\"].bind(\"mouseover\", over)\n", "document[\"mycircle\"].bind(\"mouseout\", out)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Manipulating the IPython notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An example to hide or show the code cells using a button." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c manipulating\n", "from browser import document, html\n", "\n", "def hide(ev):\n", " divs = document.get(selector = 'div.input')\n", " for div in divs:\n", " div.style.display = \"none\"\n", "\n", "def show(ev):\n", " divs = document.get(selector = 'div.input')\n", " for div in divs:\n", " div.style.display = \"inherit\"\n", "\n", "document[\"manipulating\"] <= html.BUTTON('Hide code cells', Id=\"btn-hide\")\n", "document[\"btn-hide\"].bind(\"click\", hide)\n", "\n", "document[\"manipulating\"] <= html.BUTTON('Show code cells', Id=\"btn-show\")\n", "document[\"btn-show\"].bind(\"click\", show)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "A more complete d3 example calculating things in Python and drawing results in Brython using D3.js" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A more complete D3 example. In this case, first we create some data in Python." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from random import randint\n", "\n", "n = 100\n", "x = [randint(0,800) for i in range(n)]\n", "y = [randint(0,600) for i in range(n)]\n", "r = [randint(25,50) for i in range(n)]\n", "red = [randint(0,255) for i in range(n)]\n", "green = [randint(0,255) for i in range(n)]\n", "blue = [randint(0,255) for i in range(n)]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now, the data is passed to Brython to be used in a D3 plot. In this case, the D3.js library is already loaded so it is not necessary to load it." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c other_d3 -i x y r red green blue\n", "from browser import window, document, html\n", "from javascript import JSObject\n", "\n", "d3 = window.d3\n", "\n", "WIDTH = 800\n", "HEIGHT = 600\n", "\n", "container = JSObject(d3.select(\"#other_d3\"))\n", "svg = container.append(\"svg\").attr(\"width\", WIDTH).attr(\"height\", HEIGHT)\n", "\n", "class AddShapes:\n", " def __init__(self, x, y, r, red, green, blue, shape = \"circle\", interactive = True):\n", " self.shape = shape\n", " self.interactive = interactive\n", " self._color = \"gray\"\n", " self.add(x, y, r, red, green, blue)\n", "\n", " def over(self, ev):\n", " self._color = ev.target.style.fill\n", " document[ev.target.id].style.fill = \"white\"\n", " \n", " def out(self, ev):\n", " document[ev.target.id].style.fill = self._color\n", " \n", " def add(self, x, y, r, red, green, blue):\n", " for i in range(len(x)):\n", " self.idx = self.shape + '_' + str(i) \n", " self._color = \"rgb(%s,%s,%s)\" % (red[i], green[i], blue[i])\n", " shaped = svg.append(self.shape).style(\"stroke\", \"gray\").style(\"fill\", self._color).attr(\"r\", r[i])\n", " shaped.attr(\"cx\", x[i]).attr(\"cy\", y[i]).attr(\"id\", self.idx)\n", " if self.interactive:\n", " doc[self.idx].bind(\"mouseover\", self.over)\n", " doc[self.idx].bind(\"mouseout\", self.out)\n", "\n", "plot = AddShapes(x, y, r, red, green, blue, interactive = True)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Mapping with Python in the IPython notebook using OpenLayers?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the following example we will use OpenLayers to center a map in a specific location, with a zoom and a projection and then we will draw some vector points around the location.\n", "\n", "As before, first we should load the OpenLayers.js library." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%HTML\n", "" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now we can create a map using `JSConstructor` available in the built-in Brython javascript library " ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c ol_map\n", "from browser import document, window\n", "from javascript import JSConstructor, JSObject\n", "\n", "## Div layout\n", "document['ol_map'].style.width = \"800px\"\n", "document['ol_map'].style.height = \"400px\"\n", "document['ol_map'].style.border = \"1px solid black\"\n", "\n", "OpenLayers = window.OpenLayers\n", "\n", "## Map\n", "_map = JSConstructor(OpenLayers.Map)('ol_map')\n", "\n", "## Addition of a OpenStreetMap layer\n", "_layer = JSConstructor(OpenLayers.Layer.OSM)( 'Simple OSM map')\n", "_map.addLayer(_layer)\n", "\n", "## Map centered on Lon, Lat = (-3.671416, 40.435897) and a zoom = 14\n", "## with a projection = \"EPSG:4326\" (Lat-Lon WGS84)\n", "_proj = JSConstructor(OpenLayers.Projection)(\"EPSG:4326\")\n", "_center = JSConstructor(OpenLayers.LonLat)(-3.671416, 40.435897)\n", "_center.transform(_proj, _map.getProjectionObject())\n", "_map.setCenter(_center, 10)\n", "\n", "## Addition of some points around the defined location\n", "lons = [-3.670, -3.671, -3.672, -3.672, -3.672,\n", " -3.671, -3.670, -3.670]\n", "lats = [40.435, 40.435, 40.435, 40.436, 40.437,\n", " 40.437, 40.437, 40.436]\n", "\n", "site_points = []\n", "site_style = {}\n", "\n", "points_layer = JSConstructor(OpenLayers.Layer.Vector)(\"Point Layer\")\n", "_map.addLayer(points_layer)\n", "\n", "for lon, lat in zip(lons, lats):\n", " point = JSConstructor(OpenLayers.Geometry.Point)(lon, lat)\n", " point.transform(_proj, _map.getProjectionObject())\n", " _feat = JSConstructor(OpenLayers.Feature.Vector)(point)\n", " points_layer.addFeatures(_feat)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Using Rapha\u00ebl.js" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A dummy example using rapha\u00ebl.js library.\n", "\n", "As usual, first we should include the library:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%javascript\n", "require([ \"http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js\" ], function (Raphael) {\n", " console.log(Raphael);\n", "});" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now let's make a dumb example using `JSObject`." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -c raphael_ex\n", "from browser import window\n", "from javascript import JSObject\n", "\n", "Raphael = window.Raphael\n", "\n", "paper = JSObject(Raphael(\"raphael_ex\", 400, 400))\n", "\n", "#Draw rectagle\n", "rect = paper.rect(1,1,398,398)\n", "rect.attr(\"stroke\", \"black\")\n", "\n", "#Draw orbits\n", "for rot in range(90,280,60):\n", " ellipse = paper.ellipse(200, 200, 180, 50)\n", " ellipse.attr(\"stroke\", \"gray\")\n", " ellipse.rotate(rot)\n", "\n", "#Draw nucleus\n", "nucleus = paper.circle(200,200,40)\n", "nucleus.attr(\"fill\", \"black\")\n", "\n", "# Draw electrons\n", "electron = paper.circle(200, 20, 10)\n", "electron.attr(\"fill\", \"red\")\n", "electron = paper.circle(44, 290, 10)\n", "electron.attr(\"fill\", \"yellow\")\n", "electron = paper.circle(356, 290, 10)\n", "electron.attr(\"fill\", \"blue\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Include the cell number for each cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The cells starts by 0 and all the cells (markdown, headings, code,...) has a number. If we want to re-run some cells in a programmatically way it is useful to know the number of the cells to identify them. You can delete the cell numbers using `show_cell_number(on = False)`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython\n", "from browser import doc, html\n", "\n", "def show_cell_number(on = True):\n", " cells = doc.get(selector = '.input_prompt')\n", " for i, cell in enumerate(cells):\n", " if on:\n", " if 'In' in cell.html and '
' not in cell.html:\n", " cell.html += \"
cell #\" + str(i)\n", " else:\n", " if 'In' in cell.text:\n", " cell.html = cell.html.split('
')[0]\n", "\n", "show_cell_number(on = True)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Running Python cells as a loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Imagine you have several cells of code and you want just to modify some data and run again these cells as a loop not having to create a big cell with the code of the cells together." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython\n", "from javascript import JSObject\n", "from browser import window\n", "\n", "IPython = window.IPython\n", "nb = IPython.notebook\n", "# This is used to prevent an infinite loop\n", "this_cell = nb.get_selected_index()\n", "\n", "for i in range(1,10): # Ths will run cells 1 to 9 (the beginning of the nb)\n", " cell = nb.get_cell(i)\n", " if cell.cell_type == \"code\" and i != this_cell:\n", " cell.execute()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Get the code of all the cells and create a new cell with the code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to compile all the code used in a notebook you can use this recipe (use `crtl + Enter` to run the cell if you don't want a bad behaviour):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython\n", "from javascript import JSObject\n", "from browser import window\n", "\n", "IPython = window.IPython\n", "nb = IPython.notebook\n", "this_cell = nb.get_selected_index()\n", "total_cells = nb.ncells()\n", "\n", "code = \"\"\n", "first_cell = True\n", "for i in range(total_cells):\n", " cell = nb.get_cell(i)\n", " if cell.cell_type == \"code\" and i != this_cell:\n", " if first_cell:\n", " code += \"# This cell has been generated automatically using a brython script\\n\\n\"\n", " code += \"# code from cell \" + str(i) + '\\n'\n", " first_cell = False\n", " else:\n", " code += \"\\n\\n\\n# code from cell \" + str(i) + '\\n'\n", " code += cell.get_text() + '\\n'\n", "\n", "nb.insert_cell_below('code')\n", "new_cell = nb.get_cell(this_cell + 1)\n", "new_cell.set_text(code)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Styling the nb" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lets modify a little bit the look of the notebook. Warning: The result will be very ugly..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%brython -s styling\n", "from browser import doc, html\n", "\n", "# Changing the background color\n", "body = doc[html.BODY][0]\n", "body.style = {\"backgroundColor\": \"#99EEFF\"}\n", " \n", "# Changing the color of the imput prompt\n", "inps = body.get(selector = \".input_prompt\")\n", "for inp in inps:\n", " inp.style = {\"color\": \"blue\"}\n", " \n", "# Changin the color of the output cells\n", "outs = body.get(selector = \".output_wrapper\")\n", "for out in outs:\n", " out.style = {\"backgroundColor\": \"#E0E0E0\"}\n", " \n", "# Changing the font of the text cells\n", "text_cells = body.get(selector = \".text_cell\")\n", "for cell in text_cells:\n", " cell.style = {\"fontFamily\": \"\"\"\"Courier New\", Courier, monospace\"\"\",\n", " \"fontSize\": \"20px\"}\n", " \n", "# Changing the color of the code cells.\n", "code_cells = body.get(selector = \".CodeMirror\")\n", "for cell in code_cells:\n", " cell.style = {\"backgroundColor\": \"#D0D0D0\"}" ], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }